<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px">
      <el-breadcrumb-item :to="{ path: '/backstage/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/backstage/personal/viewInfo' }">个人中心</el-breadcrumb-item>
      <el-breadcrumb-item >修改个人信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form  :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="修改头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :http-request="uploadImage"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" title="点击更换头像">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="您的姓名" prop="userName">
          <el-input prefix-icon="el-icon-s-custom" v-model="ruleForm.userName" placeholder="请输入用户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="您的性别" prop="userSex">
        <el-select v-model="ruleForm.userSex" placeholder="请选择" clearable>
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="您的电话" prop="userPhone">
          <el-input prefix-icon="el-icon-phone" v-model="ruleForm.userPhone" placeholder="请输入联系电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="您的邮箱" prop="userEmail">
          <el-input prefix-icon="el-icon-truck" v-model="ruleForm.userEmail" placeholder="请输入用户邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="您的地址" prop="userAddress">
          <el-input prefix-icon="el-icon-office-building" v-model="ruleForm.userAddress" placeholder="请输入用户地址" clearable></el-input>
      </el-form-item>
      <el-form-item label="婚姻状态" prop="userIsMarried">
        <el-select v-model="ruleForm.userIsMarried" placeholder="请选择" clearable>
          <el-option label="已婚" value="已婚"></el-option>
          <el-option label="未婚" value="未婚"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="您的身份证号" prop="userIdNumber">
          <el-input prefix-icon="el-icon-office-building" v-model="ruleForm.userIdNumber" placeholder="请输入用户身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { client } from "../../../utils/alioss";
import { getCompanyOrUserAllInfo,updateLoginUserInfo } from "../../../api/personalApi/index";
import { getStore } from '../../../storage/storage';
import { checkPhoneExist } from "../../../api/userManage/index";
export default {
  name: "EditInfo",
  data(){
     var checkPhone = (rule, value, callback) => {
        const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/
        if (!value) {
            return callback(new Error('电话号码不能为空'))
        }
        setTimeout(() => {
            if (!Number.isInteger(+value)) {
                callback(new Error('请输入数字'))
            } else {
                if (phoneReg.test(value)) {
                    const params = {
                        aid: this.ruleForm.userAid,
                        phone: this.ruleForm.userPhone,
                    }
                    checkPhoneExist(params).then(res=>{
                        if(res.data.data.isExisted === true){
                            callback(new Error('该手机号已存在，请重新输入！'));
                        }else{
                            callback();
                        }
                    });
                } else {
                  callback(new Error('电话号码格式不正确'))
                }
            }
        }, 100)
    }
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
      return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
          if (mailReg.test(value)) {
              callback()
          } else {
              callback(new Error('请输入正确的邮箱格式'))
          }   
      }, 100)
    }
    var checkIdNumber = (rule, value, callback) => {
      const mailReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (!value) {
        return callback(new Error('身份证不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
            callback()
        } else {
            callback(new Error('请输入正确的身份证格式'))
        }   
      }, 100)
    }
    return{
      imageUrl: '',
      ruleForm:{
        userAid: '', // 当前登录的用户aid
        userName: '',
        userSex: '',
        userPhone: '',
        userEmail: '',
        userAddress: '',
        userIsMarried: '',
        userIdNumber: '',
      },
      rules: {
        userName: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' }
        ],
        userSex: [
          { required: true, message: '请选择您的性别', trigger: 'change' }
        ],
        userIsMarried: [
          { required: true, message: '请选择您的婚姻状态', trigger: 'change' }
        ],
        userPhone: [
          { validator: checkPhone, trigger: ['blur','change'] }
        ],
        userEmail: [
          { validator: checkEmail, trigger: ['blur','change'] }
        ],
        userIdNumber: [
          { validator: checkIdNumber, trigger: ['blur','change'] }
        ],
        userAddress: [
          {  required: true, message: '请输入您的地址', trigger: 'blur' }
        ],
      }
    }
  },
  created(){
    // 获取当前登陆用户的所有信息
    this.getLoginUserAllInfoFunc();
  },
  methods:{
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 jpg 或 png 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isJPG && isLt5M;
    },

    // 上传图片
    uploadImage(file){
      // 定义唯一文件名
      var fileName = 'user' + `${Date.parse(new Date())}` + '.jpg';
      client().multipartUpload(fileName, file.file).then(res=>{
        this.imageUrl = 'https://recruitment-files.oss-cn-chengdu.aliyuncs.com/' + fileName;
      })
    },

     // 获取当前登陆用户的所有信息
    getLoginUserAllInfoFunc(){
      const params = {
        account: getStore("account"),
      }
      getCompanyOrUserAllInfo(params).then(res=>{
        // console.log(res);
        this.ruleForm.userAid = res.data.data.userAid;
        this.ruleForm.userName = res.data.data.userName;
        this.ruleForm.userSex = res.data.data.userSex;
        this.ruleForm.userPhone = res.data.data.userPhone;
        this.ruleForm.userEmail = res.data.data.userEmail;
        this.ruleForm.userAddress = res.data.data.userAddress;
        this.ruleForm.userIsMarried = res.data.data.userIsMarried;
        this.ruleForm.userIdNumber = res.data.data.userIdNumber;
        this.imageUrl = res.data.data.avatar ? res.data.data.avatar : 'https://recruitment-files.oss-cn-chengdu.aliyuncs.com/user1647687372000.jpg';
      })
    },

    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const data = {
              aid: this.ruleForm.userAid,
              avatar: this.imageUrl,
              name: this.ruleForm.companyName,
              phone: this.ruleForm.companyPhone,
              email: this.ruleForm.companyEmail,
              address: this.ruleForm.companyAddress,
              idNumber: this.ruleForm.userIdNumber,
              sex: this.ruleForm.userSex,
              isMarried: this.ruleForm.userIsMarried,
            }
            updateLoginUserInfo(data).then(res=>{
              this.$message.success(res.data.message);
              this.$router.push("/backstage/personal/viewInfo");
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },

    resetForm(formName) {
        this.ruleForm = {};
    },

  }
}
</script>

<style scoped>
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>